import {getCurrentWindow} from "@tauri-apps/api/window";
import {invoke} from "@tauri-apps/api/core";
import {useUserMessageStore} from "../stores/user_message.ts";
import {storeToRefs} from "pinia";
import {unListen} from "../actions/listeners.ts";


export async function windowClose() {
    const {messageMap} = storeToRefs(useUserMessageStore());
    const main = getCurrentWindow();
    await main.once("tauri://close-requested", (event) => {
        // 这里可以执行一些逻辑，比如询问用户是否真的要退出
        console.log("close-requested triggered local message:" + JSON.stringify(messageMap.value));
        const encoder = new TextEncoder();
        let params = {};
        for (let key in messageMap.value) {
            console.log("save_messages key: " + key);
            let msgs: object[] = messageMap.value[key];
            let msgList = [];
            for (let i = 0; i < msgs.length; i++) {
                let msg = {
                    sender_account: msgs[i].sender_account,
                    to_account: msgs[i].to_account,
                    message_type: msgs[i].message_type,
                    content: encoder.encode(msgs[i].content),
                }
                msgList.push(msg);
            }
            params[key] = msgList;
        }
        console.log("save_messages params: " + JSON.stringify(params));
        unListen();
        invoke("save_messages", {msg: params}).then(() => {
            console.log("save_messages successfully");
            main.destroy().then(() => {
                console.log("window closed");
            });
        });
    });
}